package reactnative.com.yftx.reactnativeintegration.nativemodule.activityresult;

import android.app.Activity;
import android.content.Intent;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import reactnative.com.yftx.reactnativeintegration.ReturnCurrentTimeActivity;
import reactnative.com.yftx.reactnativeintegration.nativemodule.RNModuleConstant;

/**
 * Created by yftx on 09/05/2017.
 */

public class RNListenActivityResultModule extends ReactContextBaseJavaModule implements ActivityEventListener {

    private static final int RESULT_ACTIVITY_REQUEST_CODE = 2389;
    private Promise mPromise;

    public RNListenActivityResultModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(this);
    }

    @Override
    public String getName() {
        return RNModuleConstant.RNListenActivityResultModuleName;
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (requestCode != RESULT_ACTIVITY_REQUEST_CODE)
            return;
        mPromise.resolve(data.getExtras().getString(ReturnCurrentTimeActivity.RESULT_KEY));
        mPromise = null;
    }

    @Override
    public void onNewIntent(Intent intent) {

    }

    @ReactMethod
    public void getCurrentTime(Promise promise) {
        mPromise = promise;
        Activity currentActivity = getCurrentActivity();
        Intent intent = new Intent(currentActivity, ReturnCurrentTimeActivity.class);
        currentActivity.startActivityForResult(intent, RESULT_ACTIVITY_REQUEST_CODE);
    }

}
